package com.daou.meeting.xmpp;

import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.MessageTypeFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

public class XmppImpl implements Xmpp {
	
	private XMPPConnection mConn = null;
	private String xmppHost = null;
	private String xmppDomain = null;
	private String xmppPort = null;
	private String xmppSenderId = null;
	private String xmppSenderPass = null;
	private XmppReceiver xmppReceiver = null;
	
	// 인증 여부를 체크하기 위한 변수
    private boolean isAuthenticated = false;
    
    public XmppImpl(XmppReceiver xmppReceiver){
    	// xmpp 접속 설정 정보를 가져온다.
        xmppHost = "mdev2.terracetech.co.kr";
        xmppPort = "5222";
        xmppDomain = "mdev2.terracetech.co.kr";
        xmppSenderPass = "1234";
        this.xmppReceiver = xmppReceiver;        
    }
    
	@Override
	public boolean connection(String id) {
        ConnectionConfiguration config = null;
        
        xmppSenderId = id;
        String host = xmppHost;
        String port = xmppPort;

        config = new ConnectionConfiguration(host, Integer.valueOf(port), xmppDomain);
        // config.setSASLAuthenticationEnabled(false);
        config.setRosterLoadedAtLogin(false);
        config.setReconnectionAllowed(true);
        config.setSendPresence(true);
        mConn = new XMPPConnection(config);
        try {
            mConn.connect();

            mConn.addConnectionListener(new ConnectionListener() {

                @Override
                public void reconnectionSuccessful() {
                    isAuthenticated = true;
                }

                @Override
                public void reconnectionFailed(Exception e) {
                    isAuthenticated = false;
                }

                @Override
                public void reconnectingIn(int seconds) {
                }

                @Override
                public void connectionClosedOnError(Exception e) {
                    isAuthenticated = false;
                }

                @Override
                public void connectionClosed() {
                    isAuthenticated = false;
                }
            });
            
            mConn.addPacketListener(mErrorListener, new MessageTypeFilter(Message.Type.error));
            mConn.addPacketListener(mChatListener, new MessageTypeFilter(Message.Type.chat));

        } catch (XMPPException e1) {
            if (e1.getXMPPError() == null) {
            } else {
            }
            return false;
        }

        return loginXmpp(id);
    }

	private boolean loginXmpp(String id) {
		String resource = null;
        try {
            resource = "push_receiver_retry";
            mConn.login(xmppSenderId, xmppSenderPass, resource);

        } catch (XMPPException e) {

            if (e.getXMPPError() == null) {
            } else {
            }
            return false;
        }

        Presence presence = new Presence(Presence.Type.available);
        mConn.sendPacket(presence);

        
        // 인증이 완료됬다고 가정 함.
        isAuthenticated = true;

        return true;
	}
	
	private PacketListener mChatListener = new PacketListener() {

        @Override
        public void processPacket(Packet packet) {

            org.jivesoftware.smack.packet.Message message = (org.jivesoftware.smack.packet.Message) packet;

            // 요청 받은 값 처리 
            JSONObject jobj = (JSONObject) JSONValue.parse(message.getBody());
            int pageIdx = Integer.valueOf(jobj.get("idx").toString());
            xmppReceiver.receivePageIndex(pageIdx);
        }
    };

    private PacketListener mErrorListener = new PacketListener() {
        @Override
        public void processPacket(Packet packet) {

            org.jivesoftware.smack.packet.Message message = (org.jivesoftware.smack.packet.Message) packet;

        }
    };
    
    private PacketListener mSendingListener = new PacketListener() {
        @Override
        public void processPacket(Packet packet) {

        }
    };

	@Override
	public boolean sendMsg(int pageIndex) {
		String listenId = xmppSenderId + "@" + xmppDomain;

        try {
            String toUser = "test2" + "@" + xmppDomain;
            org.jivesoftware.smack.packet.Message msg = new org.jivesoftware.smack.packet.Message(toUser,
                    org.jivesoftware.smack.packet.Message.Type.chat);
            
            String message = "i" + pageIndex; 
            		
            // Receiver 클래스를 분리하기 위해 Property 설정.
            msg.setProperty("receiver", listenId);
            msg.setBody(message);

            mConn.sendPacket(msg);
            // 패킷 아이디를 리턴한다.
        } catch (Exception e) {
        }

		return true;
	}
    
}
